<template>
  <div class="max-w-3xl mx-auto p-6">
    <h1 class="text-2xl font-semibold">去重（Remove Duplicate）</h1>

    <div class="mt-6 space-y-4">
      <label class="block">
        <div class="text-sm text-gray-600 mb-2">源文本（Source text）</div>
        <textarea v-model="inputText" rows="10" class="w-full p-3 border rounded resize-y" placeholder="在此粘贴或输入文本"></textarea>
      </label>

      <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <div class="col-span-1 sm:col-span-1">
          <div class="text-sm text-gray-600 mb-2">模式（Mode）</div>
          <select v-model="mode" class="w-full p-2 border rounded">
            <option value="line">按行去重（Line-based）</option>
            <option value="word">按单词去重（Word-based）</option>
          </select>
        </div>

        <div class="col-span-1 sm:col-span-1">
          <div class="text-sm text-gray-600 mb-2">保留策略（Keep）</div>
          <select v-model="keep" class="w-full p-2 border rounded">
            <option value="first">保留首次出现（Keep first）</option>
            <option value="last">保留最后出现（Keep last）</option>
          </select>
        </div>

        <div class="col-span-1 sm:col-span-1 flex items-end">
          <div class="text-sm text-gray-600 mb-2 w-full">
            <input type="file" accept=".txt" @change="onFileChange" class="text-sm" />
          </div>
        </div>
      </div>

      <div class="flex items-center gap-3">
        <label class="inline-flex items-center">
          <input type="checkbox" v-model="ignoreCase" class="form-checkbox" />
          <span class="ml-2 text-sm">忽略大小写</span>
        </label>
        <label class="inline-flex items-center">
          <input type="checkbox" v-model="trimSpaces" class="form-checkbox" />
          <span class="ml-2 text-sm">去除首尾空白</span>
        </label>
        <label class="inline-flex items-center">
          <input type="checkbox" v-model="preserveOrder" class="form-checkbox" />
          <span class="ml-2 text-sm">保留输入顺序（若取消则按首次/最后出现策略后排序）</span>
        </label>
      </div>

      <div class="flex items-center gap-3">
        <button @click="applyDedup" class="bg-blue-600 text-white px-4 py-2 rounded">去重</button>
        <button @click="copyResult" class="border px-3 py-2 rounded">复制结果</button>
        <button @click="downloadResult" class="border px-3 py-2 rounded">下载结果</button>
        <button @click="reset" class="border px-3 py-2 rounded text-sm">重置</button>
      </div>

      <div class="pt-4 border-t">
        <div class="flex justify-between items-center">
          <div class="text-sm text-gray-600">预览（Preview） — 去重后文本</div>
          <div class="text-sm text-gray-500">原始: <span class="font-medium">{{ originalCount }}</span>  唯一: <span class="font-medium">{{ uniqueCount }}</span>  重复: <span class="font-medium">{{ duplicateCount }}</span></div>
        </div>
        <textarea :value="dedupedText" rows="10" class="w-full p-3 border rounded mt-3 bg-gray-50" readonly></textarea>
      </div>

      <nuxt-link to="/text-tools" class="mt-2 inline-block text-blue-500">返回文本工具</nuxt-link>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useTools } from '~/composables/useTools'

const { copyToClipboard, downloadFile, readFile } = useTools()

const inputText = ref('')
const mode = ref('line') // 'line' | 'word'
const keep = ref('first') // 'first' | 'last'
const ignoreCase = ref(false)
const trimSpaces = ref(false)
const preserveOrder = ref(true)

const splitToItems = (text) => {
  if (!text) return []
  if (mode.value === 'line') return text.split(/\r?\n/)
  return text.split(/\s+/).filter(Boolean)
}

const itemsArray = computed(() => splitToItems(inputText.value))

const processItems = (items) => {
  const map = new Map()
  items.forEach((raw, idx) => {
    let key = raw
    if (trimSpaces.value) key = key.trim()
    if (ignoreCase.value) key = key.toLowerCase()
    if (!map.has(key)) {
      map.set(key, { original: raw, firstIdx: idx, lastIdx: idx })
    } else {
      const v = map.get(key)
      v.lastIdx = idx
      map.set(key, v)
    }
  })

  // collect entries
  let entries = Array.from(map.values())

  // determine order of output
  if (preserveOrder.value) {
    // If preserving order, sort by the index that corresponds to the keep strategy
    if (keep.value === 'first') entries.sort((a, b) => a.firstIdx - b.firstIdx)
    else entries.sort((a, b) => a.lastIdx - b.lastIdx)
  } else {
    // If not preserving order, still return deterministic order: by firstIdx (or lastIdx)
    if (keep.value === 'first') entries.sort((a, b) => a.firstIdx - b.firstIdx)
    else entries.sort((a, b) => a.lastIdx - b.lastIdx)
  }

  return entries.map(e => e.original)
}

const dedupedItems = computed(() => processItems(itemsArray.value))

const dedupedText = computed(() => {
  return mode.value === 'line' ? dedupedItems.value.join('\n') : dedupedItems.value.join(' ')
})

const originalCount = computed(() => itemsArray.value.length)
const uniqueCount = computed(() => dedupedItems.value.length)
const duplicateCount = computed(() => originalCount.value - uniqueCount.value)

const applyDedup = () => {
  inputText.value = dedupedText.value
}

const copyResult = async () => {
  const ok = await copyToClipboard(dedupedText.value)
  if (ok) alert('已复制到剪贴板')
  else alert('复制失败，请手动复制')
}

const downloadResult = () => {
  downloadFile(dedupedText.value, 'dedup-result.txt', 'text/plain')
}

const reset = () => {
  inputText.value = ''
  mode.value = 'line'
  keep.value = 'first'
  ignoreCase.value = false
  trimSpaces.value = false
  preserveOrder.value = true
}

const onFileChange = async (e) => {
  const f = e.target.files && e.target.files[0]
  if (!f) return
  try {
    const content = await readFile(f)
    inputText.value = content
  } catch (err) {
    console.error('读取文件失败', err)
    alert('读取文件失败')
  }
}
</script>
